package com.lastproject.ejb.util;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import com.lastproject.dto.RatingDTO;
import com.lastproject.ejb.entities.Book;
import com.lastproject.ejb.entities.Rating;
import com.lastproject.ejb.entities.User;

/**
 * Session Bean implementation class RatingConversion
 */
@Stateless
public class RatingConversion {

	/**
	 * Default constructor.
	 */
	@PersistenceContext
	EntityManager em;

	public RatingConversion() {
		// TODO Auto-generated constructor stub
	}

	public RatingDTO fromEntity(Rating r) {

		RatingDTO ratingDTO = new RatingDTO();

		ratingDTO.setId(r.getId());
		ratingDTO.setRating(r.getRating());
		ratingDTO.setIdBook(r.getBook().getId());
		ratingDTO.setIdUser(r.getUser().getId());

		return ratingDTO;

	}

	public Rating fromDTO(RatingDTO ratingDTO) {

		Rating rating = em.find(Rating.class, ratingDTO.getId());

		if (rating == null) {
			rating = new Rating();
		}
		rating.setBook(em.find(Book.class, ratingDTO.getIdBook()));
		rating.setUser(em.find(User.class, ratingDTO.getIdUser()));
		rating.setRating(ratingDTO.getRating());
		return rating;

	}
}
